<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\CustomerModel;
use Illuminate\Http\Request;

class Contract extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $customer_name = $request->input('customer_name', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = CustomerModel::query()->with('handle_staff')->where('is_big', 0);

        if($customer_name){
            $query->where('name', 'like', '%'.$customer_name.'%');
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $contract_invalid_date = '';
            if($item->contract_effect_date){
                $contract_invalid_date = date('Y-m-d', strtotime('+' . $item->validity_period . ' year', strtotime($item->contract_effect_date)));
            }
            $res = [
                'id' => $item->id,
                'customer_name' => $item->name,
                'customer_sn' => $item->sn,
                'contract_effect_date' => $item->contract_effect_date,
                'contract_invalid_date' => $contract_invalid_date,
                'validity_period' => $item->validity_period,
                'handle_staff_id' => $item->handle_staff_id,
                'handle_staff_name' => $item->handle_staff ? $item->handle_staff->name : '',
                'contract' => $item->contract,
                'remark' => $item->remark,
                'is_delay' => $item->is_delay,

            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function update(Request $request) {
        $id = $request->input('id', 0);
        $parmas = $request->all();

        $customer = CustomerModel::query()->find($id);
        if(!$customer){
            return $this->error('客户不存在');
        }

        $customer->contract_effect_date = $parmas['contract_effect_date'] ?? '';
        $customer->validity_period = $parmas['validity_period'] ?? 0;
        $customer->contract = $parmas['contract'] ?? '';
        $customer->handle_staff_id = $parmas['handle_staff_id'] ?? 0;
        $customer->remark = $parmas['remark'] ?? '';
        $customer->is_delay = $parmas['is_delay'] ?? 1;
        $customer->save();

        return $this->success();
    }


}
